package com.zeyu.framework.tools.logger.web;

import com.beust.jcommander.internal.Maps;
import com.zeyu.framework.core.web.BaseController;
import com.zeyu.framework.core.web.Result;
import com.zeyu.framework.tools.logger.WebPageAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;

/**
 * logger 监控和展示界面
 * Created by zeyuphoenix on 16/9/5.
 */
@Controller
@RequestMapping(value = "/tools/logger")
public class LoggerController extends BaseController {

    // ================================================================
    // Constants
    // ================================================================

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(LoggerController.class);

    // ================================================================
    // Fields
    // ================================================================

    /**
     * Spring-WebSocket内置的一个消息发送工具，可以将消息发送到指定的客户端
     */
    @Autowired
    private SimpMessagingTemplate template;

    // ================================================================
    // Constructors
    // ================================================================

    // ================================================================
    // Methods from/for super Interfaces or SuperClass
    // ================================================================

    // ================================================================
    // Public or Protected Methods
    // ================================================================

    /**
     * logger页面
     */
    @RequestMapping(value = {"index", ""})
    public String index() {
        return "modules/tools/logMonitor";
    }

    /**
     * logger页面
     */
    @RequestMapping(value = "all")
    public String all() {
        return "modules/tools/logViewer";
    }

    /**
     * 其它页面调用关闭,先接受信息,然后调用发送关闭指令
     */
    @RequestMapping(value = "close")
    @ResponseBody
    public Result disconnect(String socketKey) {

        Map<String, String> rets = Maps.newHashMap();
        rets.put("key", socketKey);
        rets.put("command", "close");

        template.convertAndSend("/topic/logger-info", rets);

        return new Result(Result.SUCCESS, "ok, close web socket");
    }

    @MessageMapping("/login-check")
    // 消息的目的地, 客户端发起连接后，订阅服务端消息时指定的一个地址，用于接收服务端的返回
    @SendTo("/topic/logger-info")
    public Result login(String message) throws Exception {
        logger.info("login is ok, receive message is : " + message);
        WebPageAppender.addSocket();
        return new Result(Result.SUCCESS, "login is ok, receive message is : " + message);
    }

    @MessageMapping("/logout-check")
    // 消息的目的地, 客户端发起连接后，订阅服务端消息时指定的一个地址，用于接收服务端的返回
    @SendTo("/topic/logger-info")
    public Result logout(String message) throws Exception {
        logger.info("logout is ok, receive message is : " + message);
        WebPageAppender.deleteSocket();
        return new Result(Result.SUCCESS, "logout is ok, receive message is : " + message);
    }


    @RequestMapping(value = "read")
    @ResponseBody
    public Map<String, String> read(long position) {

        Map<String, String> rets = Maps.newHashMap();

        StringBuilder builder = new StringBuilder("");

        String path = WebPageAppender.getFile();
        //文件路径,jar需要测试
        logger.debug("log file path is {}", path);
        RandomAccessFile randomFile;
        try {
            randomFile = new RandomAccessFile(path, "r");
            if (position < 0) {
                position = 0;
            }
            randomFile.seek(position);

            String tmp;
            // 每次最多取得200行
            int count = 0;
            while ((tmp = randomFile.readLine()) != null && count < 200) {
                // 按行读取 本编码格式
                // StringEscapeUtils.escapeHtml4(line)
                builder.append(new String(tmp.getBytes("ISO-8859-1"), "UTF-8"));
                builder.append("$$$$$");
                count++;
            }

            // 设置新的读入点
            position = randomFile.getFilePointer();
        } catch (IOException e) {
            logger.error("read log file error: ", e);
        }

        rets.put("position", position + "");
        rets.put("data", builder.toString());
        return rets;
    }

    // ================================================================
    // Getter & Setter
    // ================================================================

    // ================================================================
    // Private Methods
    // ================================================================

    // ================================================================
    // Inner or Anonymous Class
    // ================================================================

    // ================================================================
    // Test Methods
    // ================================================================

}
